package com.cinyi.cyds.base.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.cinyi.cyds.base.bean.Resource;
import com.cinyi.cyds.base.bean.SessionInfo;
import com.cinyi.cyds.base.bean.Tree;
import com.cinyi.cyds.base.model.Tresource;
import com.cinyi.cyds.base.model.Tresourcetype;
import com.cinyi.cyds.base.model.Trole;
import com.cinyi.cyds.base.model.Tuser;
import com.cinyi.cyds.base.service.ResourceServiceI;
import com.cinyi.ormlite.web.dao.DefaultJdbcDaoImpl;

@Service
public class ResourceServiceImpl implements ResourceServiceI {

	private DefaultJdbcDaoImpl<Tuser> userDao;
	private DefaultJdbcDaoImpl<Tresourcetype> resourceTypeDao;
	private DefaultJdbcDaoImpl<Tresource> resourceDao;
	private DefaultJdbcDaoImpl<Trole> roleDao;

	public ResourceServiceImpl() {
		userDao = new DefaultJdbcDaoImpl<Tuser>();
		resourceTypeDao = new DefaultJdbcDaoImpl<Tresourcetype>();
		resourceDao = new DefaultJdbcDaoImpl<Tresource>();
		roleDao =  new DefaultJdbcDaoImpl<Trole>();
	}

	@Override
	public List<Tree> tree(SessionInfo sessionInfo) throws Exception {
		List<Tresource> l = null;
		List<Tree> lt = new ArrayList<Tree>();

		List<Object> params = new ArrayList<Object>();
		params.add("0");// 菜单类型的资源

		if (sessionInfo != null) {
			l = resourceDao
					.findBySQL(
							Tresource.class,
							"select distinct t.ID as id,t.ICON as icon,t.NAME as name,t.REMARK as remark,t.SEQ as seq,t.URL as url,t.PID as pid,t.tresourcetypeId as tresourcetypeId from tresource t where tresourcetypeId = 0 and id in (select tresource_id from trole_tresource where trole_id in(select trole_id from tuser_trole where tuser_id = '"
									+ sessionInfo.getId()
									+ "')) order by t.seq");
		} else {
			l = resourceDao
					.findBySQL(
							Tresource.class,
							"select distinct t.ID as id,t.ICON as icon,t.NAME as name,t.REMARK as remark,t.SEQ as seq,t.URL as url,t.PID as pid,t.tresourcetypeId as tresourcetypeId from tresource where tresourcetypeId = 0 order by t.seq");
		}

		if (l != null && l.size() > 0) {
			for (Tresource r : l) {
				Tresourcetype tresourcetype = resourceTypeDao.get(
						r.getTresourcetypeId(), Tresourcetype.class);
				r.setTresourcetype(tresourcetype);
				Tree tree = new Tree();
				BeanUtils.copyProperties(r, tree);
				if (StringUtils.isNotBlank(r.getPid())) {
					Tresource resource = resourceDao.get(r.getPid(),
							Tresource.class);
					if (resource != null) {
						tree.setPid(resource.getId());
					}
				}
				tree.setText(r.getName());
				tree.setIconCls(r.getIcon());
				Map<String, Object> attr = new HashMap<String, Object>();
				attr.put("url", r.getUrl());
				tree.setAttributes(attr);
				lt.add(tree);
			}
		}
		return lt;
	}

	@Override
	public List<Tresource> getResourceByUser(String id) throws Exception {
		List<Tresource> l = null;
		l = resourceDao
				.findBySQL(
						Tresource.class,
						"select distinct t.ID as id,t.ICON as icon,t.NAME as name,t.REMARK as remark,t.SEQ as seq,t.URL as url,t.PID as pid,t.tresourcetypeId as tresourcetypeId from tresource t where id in (select tresource_id from trole_tresource where trole_id in(select trole_id from tuser_trole where tuser_id = '"
								+ id + "')) order by t.seq");
		return l;
	}

	@Override
	public List<Tree> allTree(SessionInfo sessionInfo) throws Exception {
		List<Tresource> l = null;
		List<Tree> lt = new ArrayList<Tree>();

		Map<String, Object> params = new HashMap<String, Object>();
		if (sessionInfo != null) {
			params.put("userId", sessionInfo.getId());// 查自己有权限的资源
			// l = resourceDao
			// .findBySQL(
			// Tresource.class,
			// "select distinct t.ID as id,t.ICON as icon,t.NAME as name,t.REMARK as remark,t.SEQ as seq,t.URL as url,t.PID as pid,t.tresourcetypeId as tresourcetypeId from tresource t where id in (select tresource_id from trole_tresource where trole_id in(select trole_id from tuser_trole where tuser_id = '"
			// + sessionInfo.getId()
			// + "')) order by t.seq");
			l = getResourceByUser(sessionInfo.getId());

		} else {
			l = resourceDao.find(new Tresource());
		}

		if (l != null && l.size() > 0) {
			for (Tresource r : l) {
				Tresourcetype tresourcetype = resourceTypeDao.get(
						r.getTresourcetypeId(), Tresourcetype.class);
				r.setTresourcetype(tresourcetype);
				Tree tree = new Tree();
				BeanUtils.copyProperties(r, tree);
				if (StringUtils.isNotBlank(r.getPid())) {
					Tresource resource = resourceDao.get(r.getPid(),
							Tresource.class);
					if (resource != null) {
						tree.setPid(resource.getId());
					}
				}
				tree.setText(r.getName());
				tree.setIconCls(r.getIcon());
				Map<String, Object> attr = new HashMap<String, Object>();
				attr.put("url", r.getUrl());
				tree.setAttributes(attr);
				lt.add(tree);
			}
		}
		return lt;
	}

	@Override
	public List<Resource> treeGrid(SessionInfo sessionInfo) throws Exception {
		List<Tresource> l = null;
		List<Resource> lr = new ArrayList<Resource>();

		Map<String, Object> params = new HashMap<String, Object>();
		if (sessionInfo != null) {
			params.put("userId", sessionInfo.getId());// 自查自己有权限的资源
			// l = resourceDao
			// .findBySQL(
			// Tresource.class,
			// "select distinct t.ID as id,t.ICON as icon,t.NAME as name,t.REMARK as remark,t.SEQ as seq,t.URL as url,t.PID as pid,t.tresourcetypeId as tresourcetypeId from tresource t where id in (select tresource_id from trole_tresource where trole_id in(select trole_id from tuser_trole where tuser_id = '"
			// + sessionInfo.getId()
			// + "')) order by t.seq");
			l = getResourceByUser(sessionInfo.getId());

		} else {
			l = resourceDao.find(new Tresource());
		}

		if (l != null && l.size() > 0) {
			for (Tresource t : l) {
				Tresourcetype tresourcetype = resourceTypeDao.get(
						t.getTresourcetypeId(), Tresourcetype.class);
				t.setTresourcetype(tresourcetype);
				Resource r = new Resource();
				BeanUtils.copyProperties(t, r);
				if (StringUtils.isNotBlank(r.getPid())) {
					Tresource resource = resourceDao.get(r.getPid(),
							Tresource.class);
					if (resource != null) {
						r.setPid(resource.getId());
						r.setPname(resource.getName());
					}
				}
				r.setTypeId(t.getTresourcetype().getId());
				r.setTypeName(t.getTresourcetype().getName());
				if (t.getIcon() != null && !t.getIcon().equalsIgnoreCase("")) {
					r.setIconCls(t.getIcon());
				}
				lr.add(r);
			}
		}

		return lr;
	}

	@Override
	public void add(Resource resource, SessionInfo sessionInfo)
			throws Exception {
		Tresource t = new Tresource();
		t.save();
		BeanUtils.copyProperties(resource, t);
		if (resource.getPid() != null
				    &&  !resource.getPid().equalsIgnoreCase("")) {
			t.setTresource(resourceDao.get(resource.getPid(), Tresource.class));
			t.setPid(resource.getPid());
		}
		if (resource.getTypeId() != null
				    &&  !resource.getTypeId().equalsIgnoreCase("")) {
			t.setTresourcetype(resourceTypeDao.get(resource.getTypeId(),Tresourcetype.class));
			t.setTresourcetypeId(Integer.parseInt(resource.getTypeId()));
		}
		if (resource.getIconCls() != null
				    &&  !resource.getIconCls().equalsIgnoreCase("") ) {
			t.setIcon(resource.getIconCls());
		}
		resourceDao.save(t);

		// 由于当前用户所属的角色，没有访问新添加的资源权限，所以在新添加资源的时候，将当前资源授权给当前用户的所有角色，以便添加资源后在资源列表中能够找到
		Tuser user = userDao.get(sessionInfo.getId(), Tuser.class);

		List<Trole> roles = getRolesByUser(user.getId());
		for (Trole r : roles) {
			r.getTresources().add(t);
			addRoleResource(r.getId(), t.getId());
		}
	}

	public void addRoleResource(String roleid, String resourceid)
			throws Exception {
		List<Object> params = new ArrayList<Object>();
		params.add(roleid);
		params.add(resourceid);
		String role_resource_sql = "insert into trole_tresource(trole_id,tresource_id) values(?,?)";
		roleDao.executeSQL(role_resource_sql, params);
	}

	public List<Trole> getRolesByUser(String id) throws Exception {
		String role_sql = "select distinct t.ID as id,t.NAME as name,t.REMARK as remark,t.SEQ as seq,t.PID as pid from trole t where id in(select trole_id from tuser_trole where tuser_id = '"
				+ id + "')";
		List<Trole> roles = roleDao.findBySQL(Trole.class, role_sql);
		return roles;
	}

	@Override
	public void delete(String id) throws Exception {
		Tresource t = resourceDao.get(id, Tresource.class);
		del(t);
	}

	private void del(Tresource t) throws Exception {
		String resource_sql = "select t.id from tresource t where t.pid = '"
				+ t.getId() + "'";
		List<Tresource> resources = resourceDao.findBySQL(Tresource.class,
				resource_sql);
		if (resources != null && resources.size() > 0) {
			for (Tresource r : resources) {
				del(r);
			}
		}
		resourceDao.delete(t.getId(), Tresource.class);
	}

	@Override
	public void edit(Resource resource) throws Exception {
		Tresource t = resourceDao.get(resource.getId(), Tresource.class);
		if (t != null) {
			BeanUtils.copyProperties(resource, t);
			if (resource.getTypeId() != null
					&& !resource.getTypeId().equalsIgnoreCase("")) {
				t.setTresourcetype(resourceTypeDao.get(resource.getTypeId(),
						Tresourcetype.class));// 赋值资源类型
				t.setTresourcetypeId(Integer.parseInt(resource.getTypeId()));
			}
			if (resource.getIconCls() != null
					&& !resource.getIconCls().equalsIgnoreCase("")) {
				t.setIcon(resource.getIconCls());
			}
			if (resource.getPid() != null
					&& !resource.getPid().equalsIgnoreCase("")) {// 说明前台选中了上级资源
				Tresource pt = resourceDao.get(resource.getPid(),
						Tresource.class);
				isChildren(t, pt);// 说明要将当前资源修改到当前资源的子/孙子资源下
				t.setTresource(pt);
				t.setPid(resource.getPid());
			} else {
				t.setTresource(null);// 前台没有选中上级资源，所以就置空
				t.setPid(null);
			}
		}
		resourceDao.saveOrUpdate(t);
	}

	/**
	 * 判断是否是将当前节点修改到当前节点的子节点
	 * 
	 * @param t
	 *            当前节点
	 * @param pt
	 *            要修改到的节点
	 * @return
	 * @throws T
	 */
	private boolean isChildren(Tresource t, Tresource pt) throws Exception {
		if (pt != null) {
			if (pt.getPid() != null) {
				Tresource resource = resourceDao.get(pt.getPid(),
						Tresource.class);
				if (resource != null) {
					if (resource.getId().equalsIgnoreCase(t.getId())) {
						pt.setTresource(null);
						pt.setPid(null);
						return true;
					} else {
						return isChildren(t, resource);
					}
				}
			}
		}
		return false;
	}

	@Override
	public Resource get(String id) throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", id);
		Tresource t = resourceDao.get(id, Tresource.class);
		Tresourcetype tresourcetype = resourceTypeDao.get(
				t.getTresourcetypeId(), Tresourcetype.class);
		t.setTresourcetype(tresourcetype);
		Resource r = new Resource();
		BeanUtils.copyProperties(t, r);
		if (StringUtils.isNotBlank(r.getPid())) {
			Tresource resource = resourceDao.get(r.getPid(), Tresource.class);
			if (resource != null) {
				r.setPid(resource.getId());
				r.setPname(resource.getName());
			}
		}
		r.setTypeId(t.getTresourcetype().getId());
		r.setTypeName(t.getTresourcetype().getName());
		if (t.getIcon() != null && !t.getIcon().equalsIgnoreCase("")) {
			r.setIconCls(t.getIcon());
		}
		return r;
	}

}
